#!/usr/bin/perl -w
use strict;
use warnings;
use File::Copy;

#Two files are needed: 1) pdb formated protein structure 2) list of variations
if ($#ARGV != 2) {die "Program used with parameters [pdb] [chainID] [list of variations]\n";}

########preparation#############
my @tab = split (/\//,$ARGV[0]);
my $name = $tab[-1];
my $pdb= $name;
$name =~ s/.pdb//;
mkdir $name;

#chain ID
my $chID =$ARGV[1];

#parse_variations
my @variations=open_file($ARGV[2]);
my ($string);
foreach my $var(@variations){
	my $AA=substr($var,0,1);
	my $pos=substr($var,1);
	$pos =~ s/[A-Z]+//;
	my $kod = $AA.$chID.$pos."a";
	if ($string) {$string = $string.",".$kod;}
	else {$string = $kod;}
}

######RUN##############
#change directory and save files
chdir $name or die "directory $name not present: $!";
copy("$ARGV[0]","$pdb") or die "Copy $ARGV[0] failed: $!";
my $path = `which FoldX.linux64`;
$path =~ s/FoldX.linux64\n$//;
copy("$path/rotabase.txt","rotabase.txt") or die "Copy $path/rotabase.txt failed: $!";

#structure file list
`echo  $pdb > list.txt `;

#prepare input file
open(FLDX, "> in-foldx_energy") or die "Can not open an input file: $!";
print FLDX "\<TITLE\>FOLDX_runscript\;\n";
print FLDX "\<JOBSTART\>\#\;\n";
print FLDX "\<PDBS\>\#\;\n";
print FLDX "\<BATCH\>list.txt\;\n";
print FLDX "\<COMMANDS\>FOLDX_commandfile;\n";
print FLDX "\<PositionScan\>foldx-scan.out\,$string\;\n";
print FLDX "\<END\>\#;\n";
print FLDX "\<OPTIONS\>FOLDX_optionfile\;\n";
print FLDX "\<Temperature\>298\;\n";
print FLDX "\<R\>\#\;\n";
print FLDX "\<pH\>7\;\n";
print FLDX "\<IonStrength\>0.050\;\n";
print FLDX "\<water\>-CRYSTAL\;\n";
print FLDX "\<metal\>-CRYSTAL\;\n";
print FLDX "\<VdWDesign\>2\;\n";
print FLDX "\<OutPDB\>false\;\n";
print FLDX "\<pdb_hydrogens\>false\;\n";
print FLDX "\<complex_with_DNA\> true\;\n";
print FLDX "\<END\>\#\;\n";
print FLDX "\<JOBEND\>\#\;\n";
print FLDX "\<ENDFILE\>\#\;\n";

#foldxX run options
open(OPT, "> opt-scan") or die "Can not open an input file: $!";
print OPT "3\n";
print OPT "in-foldx_energy\n";

#run FoldX
`FoldX.linux64 < opt-scan > energies-scan.out`;
 
 
sub open_file{
  my ($file_name)=@_;
  open(INP1, "< $file_name") or die "Can not open an input file: $!";
  my @file1=<INP1>;
  close (INP1);
  chomp @file1;
  return @file1;
}		